﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace H.Utils.DataStruct
{
    /// <summary>
    /// 弱引用对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public class WeakObject<T> : WeakReference
    {
        /// <summary>
        /// 将一个对象包装为弱引用对象
        /// </summary>
        /// <param name="obj"></param>
        public WeakObject(T obj) : base(obj) { }

        /// <summary>
        /// 序列化构造器
        /// </summary>
        /// <param name="serializationInfo"></param>
        /// <param name="streamingContext"></param>
        protected WeakObject(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
        {
        }

        public override int GetHashCode()
        {
            return IsAlive ? Target.GetHashCode() : base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (IsAlive)
            {
                if (obj is T t)
                {
                    return Equals(t, Target);
                }
                else if (obj is WeakObject<T> t2)
                {
                    if (t2.IsAlive)
                    {
                        return Equals(Target, t2.Target);
                    }
                    else
                    {
                        return ReferenceEquals(this, t2);
                    }
                }
            }
            else
            {
                if (obj is WeakObject<T> t2)
                {
                    return ReferenceEquals(this, t2);
                }
            }
            return false;
        }
    }
}
